package com.esd.device.utils;

public class ResultUtils {

    // 校验返回结果是否正确
    public static boolean checkResult(String command, String resultStr) {
        if (resultStr == null || resultStr.equals("")){
            return false;
        }
        command = command.toUpperCase().replace(" ", "") ;
        resultStr = resultStr.toUpperCase().replace(" ", "") ;

        if (resultStr.length() % 2 != 0){
            return false;
        }
        if(command.length()>=10&&resultStr.length()>=10){
            String command1 = command.substring(0,10) ;
            String resultStr1 = resultStr.substring(0,10) ;
            return command1.equals(resultStr1) ;
//            if (!command1.equals(resultStr1)){
//                return false ;
//            }
//            byte[] bytes = hexString2Bytes(resultStr.substring(0 , resultStr.length() - 4));
//            String crc = stringPolishing(getCRC(bytes)).toUpperCase();
//            String s = resultStr.substring(resultStr.length() - 4).toUpperCase();
//            return s.equals(crc) ;
        }else {
            return false;
        }
    }

    private static String stringPolishing(String Str) {
        int length = Str.length();
        StringBuilder StrBuilder = new StringBuilder(Str);
        for (int i = 0; i < (4 - length); i++) {
            StrBuilder.insert(0, "0");
        }
        return StrBuilder.toString();
    }

    private static String getCRC(byte[] bytes) {
        int CRC = 0x0000ffff;
        int POLYNOMIAL = 0x0000a001;
        int i, j;
        for (i = 0; i < bytes.length; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        return Integer.toHexString(CRC);
    }

    private static byte[] hexString2Bytes(String hexStr) {
        hexStr = hexStr.replace(" ", "");
        byte[] b = new byte[hexStr.length() / 2];
        int j = 0;
        for (int i = 0; i < b.length; i++) {
            char c0 = hexStr.charAt(j);
            char c1 = hexStr.charAt(j+1);
            j += 2;
            b[i] = (byte) Integer.parseInt(c0 + "" + c1, 16); // 将16进制字符串转 byte
        }
        return b;
    }

    public static String formatResult(String resultStr) {
        if (resultStr.isEmpty()){
            return resultStr ;
        }
        String s = resultStr.replace(" ", "").toUpperCase();
        int i = 2 ;
        StringBuilder sb = new StringBuilder();
        sb.append(s, 0, 2) ;
        if(s.length() > 2){
            while (i < s.length()){
                sb.append(" ").append(s, i, i+2);
                i += 2;
            }
        }
        return sb.toString();
    }
}
